<?php
namespace app\index\controller;

use think\Controller;
use think\Db;
use app\index\model\Mail;

class Mails extends Controller
{
    /*
     * 邮件类型
     */
    private $_mail_type = [
        '0' => '其它',
        '1' => '产品质量',
        '2' => '操作说明',
        '3' => '产品咨询',
    ];
    public function __construct(){

    }
    public function index()
    {
        $prod_id = input('param.prod_id');

        if(!$prod_id){
            $this->redirect('products/index');
        }

        $mails = db('mail')->where('prod_id',$prod_id)->order('mail_date','asc')->select();

        return view('index',['data' => $mails,'prod_id'=>$prod_id,'mail_type'=>$this->_mail_type]);
    }

    public function add_mail(){
        $prod_id = input('prod_id');

        if(!$prod_id){
            $this->error('非法操作');
        }

        return view('add_mail',['prod_id'=>$prod_id,'mail_type'=>$this->_mail_type]);
    }

    public function do_add_mail(){
        $prod_id = input('prod_id');
        $mail = new Mail();

        $mail->name = input('name');
        $mail->type = input('type');
        $mail->mail_date = input('mail_date');
        $mail->prod_id = $prod_id;

        try {
            $res = $mail->save();
        }catch (\Exception $e) {
            $this->error($e->getMessage());
            exit;
        }

        if($res){
            $this->redirect('index',['prod_id'=>$prod_id]);
        }else{
            $this->error('添加邮件出错');
        }
    }

    public function do_delete(){
        $mail_id = input('mail_id');
        $prod_id = input('prod_id');

        try {
            $res = Mail::destroy($mail_id);
        }catch (\Exception $e) {
            $this->error($e->getMessage());
            exit;
        }

        if($res){
            $this->redirect('index',['prod_id'=>$prod_id]);
        }else{
            $this->error('删除邮件出错');
        }
    }
}
